package com.daqsoft.controller.project;

import com.daqsoft.data.Message;
import com.daqsoft.data.User;
import com.daqsoft.data.project.Node;
import com.daqsoft.data.project.Project;
import com.daqsoft.data.project.ProjectUser;
import com.daqsoft.data.project.Task;
import com.daqsoft.dto.GeneralResultEnum;
import com.daqsoft.dto.StatusEnum;
import com.daqsoft.dto.TaskTypeEnum;
import com.daqsoft.permission.Verify;
import com.daqsoft.permission.VerifyType;
import com.daqsoft.service.NoticeService;
import com.daqsoft.service.project.NodeService;
import com.daqsoft.service.project.ProjectService;
import com.daqsoft.service.project.TaskService;
import com.daqsoft.service.system.UserManageService;
import com.daqsoft.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 任务控制器
 *
 * @author 周麟东 on 12:06
 */
@RestController
@RequestMapping("task")
public class TaskController {

    @Autowired
    private TaskService taskService;
    @Autowired
    private NodeService nodeService;
    @Autowired
    private UserManageService userService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private NoticeService noticeService;

    @RequestMapping("getTaskByNodeId")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "获取任务列表")
    public GeneralResultEnum getTasks(int nodeId) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Task task : taskService.getTaskByNode(nodeId)) {
            list.add(task.toMap());
        }
        return GeneralResultEnum.SUCCESS.setData(list).setDesc("获取任务列表成功");
    }

    @RequestMapping("save")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "保存任务")
    public GeneralResultEnum saveTask(HttpServletRequest request, int verifierId, int nodeId, Task task, int pid) {
        User user = (User) request.getSession().getAttribute("user");
        Node node = nodeService.get(nodeId);
        //检查本身的日期合理性
        if (task.getEndDate().getTime() < task.getStartDate().getTime()) {
            return GeneralResultEnum.FAIL.setDesc("该任务的开始时间大于结束时间,请重新设置");
        }
        task.setMsg(Log.format(new Date(), user, "<i>#创建任务#</i>"));
        return GeneralResultEnum.SUCCESS.setData(taskService.save(verifierId, node, task, pid, TaskTypeEnum.SIMPLE).toMap()).setDesc("保存任务成功");
    }

    @RequestMapping("remove")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "删除任务")
    public GeneralResultEnum removeTask(int id) {
        if (taskService.remove(id)) {
            return GeneralResultEnum.SUCCESS.setDesc("删除任务成功");
        }
        return GeneralResultEnum.FAIL.setDesc("删除任务失败");
    }

    @RequestMapping("getUserTasks")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "获取用户的任务")
    public GeneralResultEnum getUserTasks(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        List<Map<String, Object>> list = new ArrayList<>();
        for (Task task : taskService.getTaskByPrincipal(user, true)) {
            if (task.getProject().getId() == 45){
                System.out.println(task.getProject().getStatus());
            }
            if (task.getType() == TaskTypeEnum.SIMPLE){
                if (task.getProject().getStatus() == StatusEnum.HIDDEN || task.getProject().getStatus() == StatusEnum.CHANGING || task.getProject().getStatus() == StatusEnum.HIDDEN_CAN_CHANGE || task.getProject().getStatus() == StatusEnum.CHANGED) {
                    continue;
                }
            }

            list.add(task.toMap());
        }
        for (Task task : taskService.getTaskByVerifier(user, true)) {
            if (task.getType() == TaskTypeEnum.SIMPLE) {
                if (task.getProject().getStatus() == StatusEnum.HIDDEN || task.getProject().getStatus() == StatusEnum.CHANGING || task.getProject().getStatus() == StatusEnum.HIDDEN_CAN_CHANGE || task.getProject().getStatus() == StatusEnum.CHANGED) {
                    continue;
                }
            }
            if (task.getVerifier() != task.getPrincipal()) {
                list.add(task.toMap());
            }
        }
        return GeneralResultEnum.SUCCESS.setData(list);
    }

    @RequestMapping("updateTask")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "解决任务")
    public GeneralResultEnum updateTask(HttpServletRequest request, String solution, int id, boolean isSubmit) {
        User user = (User) request.getSession().getAttribute("user");
        Task task = taskService.get(id);
        if (task == null) {
            return GeneralResultEnum.FAIL.setDesc("该任务不存在");
        }
        task.setSolution(solution);
        String msg = task.getMsg();
        if (isSubmit) {
            task.setStatus(StatusEnum.CHECK);
            task.setMsg(msg + "<br>" + Log.format(new Date(), user, "<i>#提交任务#</i>"));
        } else {
            task.setMsg(msg + "<br>" + Log.format(new Date(), user, "<i>#保存任务#</i>"));
        }
        taskService.save(task);
        //通知 如果验收人不是自己那么就通知给验收人
        if (task.getVerifier().getId() != user.getId()) {
            noticeService.sendMessage(new Message(user, task.getVerifier(), "用户[" + user.getRealName() + "]已处理完任务[" + task.getName() + "]请审核", "/index.html#tasks-panel"));
        }
        return GeneralResultEnum.SUCCESS.setData(task.toMap()).setDesc("任务保存成功");
    }

    @RequestMapping("updateTaskStatus")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "更改任务状态")
    public GeneralResultEnum updateTaskStatus(HttpServletRequest request, int id, String msg, String status) {
        User user = (User) request.getSession().getAttribute("user");
        Task task = taskService.get(id);
        if (task == null) {
            return GeneralResultEnum.FAIL.setDesc("该任务不存在");
        }
        task.setStatus(StatusEnum.valueOf(status));
        String m = task.getMsg();
        task.setMsg(m + "<br>" + Log.format(new Date(), user, "<i>#更改任务状态 -> " + status + "#</i> " + msg));
        //如果任务完成了 则设置完成时间
        if (StatusEnum.valueOf(status) == StatusEnum.FINISH) {
            task.setRealEndDate(new Date());
        }
        task = taskService.save(task);
        //如果任务完成则开始检查节点所有任务是否全部都完成了
        if (StatusEnum.valueOf(status) == StatusEnum.FINISH) {
            //通知责任人任务已经通过审核
            nodeService.checkNodeFinish(task.getNode());
            noticeService.sendMessage(new Message(user, task.getPrincipal(), "用户[" + user.getRealName() + "]已通过任务[" + task.getName() + "]审核 , 恭喜", "/index.html#tasks-panel"));
        } else if (StatusEnum.valueOf(status) == StatusEnum.ERROR) {
            //通知责任人任务没有通过审核
            noticeService.sendMessage(new Message(user, task.getPrincipal(), "用户[" + user.getRealName() + "]已驳回任务[" + task.getName() + "]审核 , 请重新编辑该任务", "/index.html#tasks-panel"));
        } else if (StatusEnum.CHECKED == StatusEnum.valueOf(status) && task.getType() == TaskTypeEnum.CHANGE) {// 如果是变更需要单独处理
            task.setEndDate(new Date());
            task.setRealEndDate(new Date());
            taskService.save(task);
            task.getProject().setStatus(StatusEnum.CAN_CHANGE);
            projectService.save(task.getProject());
            noticeService.sendMessage(new Message(user, task.getVerifier(), "用户[" + user.getRealName() + "]已通过项目变更[" + task.getProject().getProjectName() + "]审核 , 恭喜", "/index.html#my-project-manage"));
        }
        return GeneralResultEnum.SUCCESS.setData(task.toMap()).setDesc("更改任务状态成功!");
    }

    @RequestMapping("updateChangeTask")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "更改正在变更的任务")
    public GeneralResultEnum updateChangeTask(String status, int verifierId, int principalId, int id) {
        Task task = taskService.get(id);
        if (task == null) {
            return GeneralResultEnum.FAIL.setDesc("任务不存在");
        }
        if (task.getProject().getStatus() != StatusEnum.CHANGING) {
            return GeneralResultEnum.FAIL.setDesc("任务所在项目不是正在变更的项目");
        }
        User verifier = userService.findOne(verifierId);
        if (verifier == null) {
            return GeneralResultEnum.FAIL.setDesc("责任人不存在");
        }
        User principal = userService.findOne(principalId);
        if (principal == null) {
            return GeneralResultEnum.FAIL.setDesc("负责人不存在");
        }
        StatusEnum statusEnum = StatusEnum.valueOf(status);
        task = taskService.updateChangeTask(task, verifier, principal, statusEnum);
        return GeneralResultEnum.SUCCESS.setData(task.toMap()).setDesc("保存变更任务成功");
    }


    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "通过项目获取日历方式")
    @RequestMapping("getTaskCalendarByProject")
    public GeneralResultEnum getTaskCalendarByProject(int projectId, int calendar) {
        Project project = projectService.get(projectId);
        List<Task> tasks = taskService.getByProject(project, true);
        List<Map<String, Object>> planList = new ArrayList<>();
        for (Task task : tasks) {
            if (task.getType() == TaskTypeEnum.SIMPLE && calendar == 2) {
                planList.add(task.toCalendarPlanMap());
            }
            if (task.getType() == TaskTypeEnum.SIMPLE && calendar == 1) {
                planList.add(task.toCalendarRealMap());
            }
        }
        return GeneralResultEnum.SUCCESS.setData(planList).setDesc("获取成功");
    }

    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "获取实际和计划")
    @RequestMapping("getTaskByType")
    public GeneralResultEnum getTaskByType() {
        List<Map<String, Object>> planList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("title", "实际");
        planList.add(map);
        map = new HashMap<>();
        map.put("id", 2);
        map.put("title", "计划");
        planList.add(map);
        return GeneralResultEnum.SUCCESS.setData(planList).setDesc("获取成功");
    }

    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "根据项目ID 获取甘特图")
    @RequestMapping("getTaskGantt")
    public GeneralResultEnum getTaskGantt(int projectId) {
        Project project = projectService.get(projectId);
        List<Task> tasks = taskService.getByProject(project, true);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Task task : tasks) {
            if (task.getType() == TaskTypeEnum.SIMPLE) {
                list.add(task.toPlanGantt());
                list.add(task.toRealGantt());
            }
        }
        return GeneralResultEnum.SUCCESS.setData(list);
    }
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "开启任务")
    @RequestMapping("openTask")
    public GeneralResultEnum openTask(int taskId) {
        Task task = taskService.get(taskId);
        task.setRealStartDate(new Date());
        task.setStatus(StatusEnum.PROCESS);
        taskService.save(task);
        //通知给负责人
        noticeService.sendMessage(new Message(task.getPrincipal(), task.getVerifier(), task.getPrincipal().getRealName() + "已开始处理任务:[" + task.getName() + "]", "/index.html#tasks-panel"));
        return GeneralResultEnum.SUCCESS.setData(task.toMap()).setDesc("开启任务成功");
    }


    @RequestMapping("pauseTask")
    @Verify(value = VerifyType.HAVE_PERMISSION, desc = "暂停任务")
    public GeneralResultEnum pauseTask(boolean isPause, int taskId, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        Task task = taskService.get(taskId);
        if (task == null) {
            return GeneralResultEnum.FAIL.setDesc("任务不存在");
        }
        if (task.getProject().getStatus() != StatusEnum.CAN_CHANGE && task.getProject().getStatus() != StatusEnum.CHANGING) {
            return GeneralResultEnum.FAIL.setDesc("该任务所属项目不是变更项目 或者已经完成了变更");
        }
        task.setMsg(Log.add(user,task.getMsg(),isPause ? "<i>暂停任务</i>" : "<i>取消暂停任务</i>"));
        task = taskService.pauseTask(task, isPause);
        //通知责任人和负责人
        if (user.getId() != task.getVerifier().getId()) {
            if (isPause) {
                noticeService.sendMessage(new Message(user, task.getVerifier(), user.getRealName() + "已经暂停了任务[" + task.getName() + "] , 该任务暂时不能被执行 , 等项目完成变更流程后才能继续执行"));
            } else {
                noticeService.sendMessage(new Message(user, task.getVerifier(), "任务[" + task.getName() + "现在可以继续执行"));
            }
        }
        if (user.getId() != task.getPrincipal().getId()) {
            if (isPause) {
                noticeService.sendMessage(new Message(user, task.getPrincipal(), user.getRealName() + "已经暂停了任务[" + task.getName() + "] , 该任务暂时不能被执行 , 等项目完成变更流程后才能继续执行"));
            }else {
                noticeService.sendMessage(new Message(user, task.getPrincipal(), "任务[" + task.getName() + "现在可以继续执行"));
            }
        }
        return GeneralResultEnum.SUCCESS.setData(task.toMap()).setDesc("暂停成功");
    }
}
